package org.leiyang.config;

import org.leiyang.common.dtos.OffLineMsgsVO;
import org.leiyang.service.RemoteCallByRSocket;
import org.springframework.messaging.rsocket.RSocketRequester;
import org.springframework.messaging.rsocket.service.RSocketServiceProxyFactory;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * RSocket相关的配置类
 */
@Component
public class RSocketConfig {
    /**
     * 用于缓存RSocketServiceProxyFactory
     */
    private final Map<String, RSocketServiceProxyFactory> cachedRSocketServiceProxyFactorys = new ConcurrentHashMap<>(2);

    private final RSocketRequester.Builder requesterBuilder;

    public RSocketConfig(RSocketRequester.Builder requesterBuilder) {
        this.requesterBuilder = requesterBuilder;
    }

    /**
     * 创建带有 @RSocketExchange注解的方法的RSocket服务接口的客户端代理，并进行方法调用
     * @param serverIpPort RSocket服务的通信地址信息
     * 注：此处默认RSocket的通信协议是基于websocket的(此处适合使用WEBSOCKET)
     */
    public Mono<Boolean> sendOffLineMsgsByRSStub(String serverIpPort, OffLineMsgsVO offLineMsgsVO) {
        RSocketServiceProxyFactory rSocketServiceProxyFactory = cachedRSocketServiceProxyFactorys.computeIfAbsent(serverIpPort, (key) -> {
            String url = "ws://".concat(key);
            RSocketRequester rsocketRequester = this.requesterBuilder.websocket(URI.create(url));
            return RSocketServiceProxyFactory.builder(rsocketRequester).build();
        });
        RemoteCallByRSocket remoteCallByRSocket = rSocketServiceProxyFactory.createClient(RemoteCallByRSocket.class);
        return remoteCallByRSocket.sendOffLineMsgsByRS(offLineMsgsVO);
    }
}
